package org.hbgl.geoentity.db.service;

import org.hbgl.geoentity.db.dao.GePermissionMapper;
import org.hbgl.geoentity.db.domain.GePermission;
import org.hbgl.geoentity.db.domain.GePermissionExample;
import org.hbgl.geoentity.db.util.EnumFile;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Service
public class GePermissionService {
    @Resource
    private GePermissionMapper permissionMapper;

    public Set<String> queryByRoleIds(Integer[] roleIds) {
        Set<String> permissions = new HashSet<>();
        if (roleIds.length == 0) {
            return permissions;
        }

        GePermissionExample example = new GePermissionExample();
        example.or().andRoleIdIn(Arrays.asList(roleIds)).andStateEqualTo(EnumFile.CommonState.Normal);
        List<GePermission> permissionList = permissionMapper.selectByExample(example);

        for (GePermission permission : permissionList) {
            String permissionStr = permission.getPermission();
            if (permissionStr.contains("@")) {
                permissionStr = permissionStr.substring(0, permissionStr.indexOf("@"));
            }
            permissions.add(permissionStr);
        }

        return permissions;
    }

    public Set<String> queryByRoleId(Integer roleId) {
        Set<String> permissions = new HashSet<>();
        if (roleId == null) {
            return permissions;
        }

        GePermissionExample example = new GePermissionExample();
        example.or().andRoleIdEqualTo(roleId).andStateEqualTo(EnumFile.CommonState.Normal);
        List<GePermission> permissionList = permissionMapper.selectByExample(example);

        for (GePermission permission : permissionList) {
            permissions.add(permission.getPermission());
        }

        return permissions;
    }

    public boolean checkSuperPermission(Integer roleId) {
        if (roleId == null) {
            return false;
        }

        GePermissionExample example = new GePermissionExample();
        example.or().andRoleIdEqualTo(roleId).andPermissionEqualTo("*").andStateEqualTo(EnumFile.CommonState.Normal);
        return permissionMapper.countByExample(example) != 0;
    }

    public List<GePermission> findByPermission(Integer roleId, String permission) {
        GePermissionExample example = new GePermissionExample();
        example.or().andRoleIdEqualTo(roleId).andPermissionLike(permission + "@%").andStateEqualTo(EnumFile.CommonState.Normal);
        return permissionMapper.selectByExample(example);
    }
}
